import axios from 'axios';
import { Notify } from 'vant';
import router from '../router';

const req = axios.create();

// 拦截器.请求拦截
req.interceptors.request.use((config) => {
    config.headers.Authorization = localStorage.getItem('TOKEN');
    return config;
});

// 拦截器.响应拦截
req.interceptors.response.use(
    (res) => {
        return res;
    },
    (err) => {
        if (err.response.status === 401) {
            router.push('/login');
        }
    },
);

export default req;

/**
 * @param { Promise<T> } promiseInstance
 * @param { (res: T) => void } onSuccess
 */
export function withMsg1 (promiseInstance, onSuccess) {
    promiseInstance
        .then((res) => {
            Notify({ type: 'success', message: res.data.message });
            onSuccess && onSuccess(res);
        })
        .catch((err) => {
            Notify({ type: 'danger', message: err.response.data.message });
        });
}

/**
 * @param { Promise<T> } promiseInstance
 * @returns { Promise<T> }
 * @description 对请求实例增加成功失败提示消息功能
 */
export function withMsg (promiseInstance) {
    return new Promise((resolve, reject) => {
        promiseInstance
            .then((res) => {
                Notify({ type: 'success', className: 'tip', message: res.data.message || 'OK' });
                resolve(res);
            })
            .catch((err) => {
                Notify({ type: 'danger', className: 'tip', message: err.response.data.message || 'NOT OK' });
                reject(err);
            });
    });
}

/**
 * @param { async function (...args): any } fn
 */
export function withLoading (fn) {
    // 模仿fn三步
    // 1. 模仿执行
    // 2. 模仿参数
    // 3. 模仿this
    return async function (...args) {
        this.loading = true;
        await fn.call(this, ...args);
        this.loading = false;
    };
}
